class ListNode {
    int val;
    ListNode next;
    ListNode(int val) {
        this.val = val;
        this.next = null;
    }
}
public class code10 {
    public static int cycleLength(ListNode head) {

        ListNode fast = head;
        ListNode slow = head;

        while(fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) {
                int len = 1;
                ListNode current = slow.next;
                while (current != slow) {
                    current = current.next;
                    len++;
                }
                return len;
            }
        }
        return 0;
    }

    public static void main(String[] args) {
        // 创建一个带环的链表：1 -> 2 -> 3 -> 4 -> 2
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);

        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node2; // 环起点是 node2

        System.out.println(cycleLength(node1));
    }
}
